# coding: utf-8

import pytz
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from db.models import db, BorrowBook
from config import app
from const import OverdueFee
from log import cronjob_logger

def check_overdue_books():
    """检查是否有逾期未还的书籍，并更新is_overdue字段"""
    cronjob_logger.info("")
    cronjob_logger.info("#"*100)
    cronjob_logger.info('job start')
    now = datetime.now()
    with app.app_context():
        overdue_books = BorrowBook.query.filter(
            BorrowBook.return_time < now, 
            BorrowBook.is_return == 0,
            BorrowBook.is_overdue == 0).all()
        cronjob_logger.info(f"过期书籍：{overdue_books}")
        
        for overdue_book in overdue_books:
            overdue_book.is_overdue = True
            overdue_book.overdue_days = (now - overdue_book.return_time).days
            overdue_book.overdue_fee = overdue_book.overdue_days * OverdueFee.FEE_PER_DAY.value
        
        db.session.commit()
    cronjob_logger.info('job finish')

def run_scheduler_job():
    scheduler = BackgroundScheduler()
    scheduler.add_job(func=check_overdue_books, trigger="interval", minutes=1)
    scheduler.start()

scheduler = BackgroundScheduler(timezone=pytz.timezone('Asia/Shanghai'))
scheduler.add_job(func=check_overdue_books, trigger="interval", minutes=1)
# scheduler.start()